package com.lesson01;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//通过反射创建对象
public class Test09 {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        //获得Class对象
        Class<?> clazz = Class.forName("com.lesson01.Student");
        //构造一个对象
        Student student = (Student) clazz.newInstance();
        System.out.println(student);

        //通过构造器创建对象
        Constructor<?> constructor = clazz.getDeclaredConstructor(String.class, int.class);
        Student student1 = (Student) constructor.newInstance();
        System.out.println(student1);

        //通过反射调用普通方法
        Student student2 = (Student) clazz.newInstance();
        System.out.println(student2.toString());
        //通过反射调用方法
        Method toString = clazz.getMethod("toString");
        Object invoke = toString.invoke(student2);
        System.out.println(invoke);
    }
}
